<template>
  <div class="navigation-bar">
    <ul>
      <li
        v-for="item in menuItems"
        :key="item.id"
        @mouseenter="showSubMenu(item.id)"
        @mouseleave="hideSubMenu(item.id)"
      >
        {{ item.label }}
        <ul
          v-if="item.showSubMenu"
          @mouseenter="showSubMenu(item.id)"
          @mouseleave="hideSubMenu(item.id)"
        >
          <li v-for="subItem in item.subMenuItems" :key="subItem.id">
            {{ subItem.label }}
          </li>
        </ul>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      menuItems: [
        {
          id: 1,
          label: "Menu 1",
          showSubMenu: false,
          subMenuItems: [
            { id: 11, label: "Submenu 1-1" },
            { id: 12, label: "Submenu 1-2" },
            { id: 13, label: "Submenu 1-3" },
          ],
        },
        {
          id: 2,
          label: "Menu 2",
          showSubMenu: false,
          subMenuItems: [
            { id: 21, label: "Submenu 2-1" },
            { id: 22, label: "Submenu 2-2" },
            { id: 23, label: "Submenu 2-3" },
          ],
        },
        {
          id: 3,
          label: "Menu 3",
          showSubMenu: false,
          subMenuItems: [
            { id: 31, label: "Submenu 3-1" },
            { id: 32, label: "Submenu 3-2" },
            { id: 33, label: "Submenu 3-3" },
          ],
        },
      ],
    };
  },
  methods: {
    showSubMenu(itemId) {
      this.menuItems.forEach((item) => {
        if (item.id === itemId) {
          item.showSubMenu = true;
        }
      });
    },
    hideSubMenu(itemId) {
      this.menuItems.forEach((item) => {
        if (item.id === itemId) {
          item.showSubMenu = false;
        }
      });
    },
  },
};
</script>

<style scoped>
.navigation-bar ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.navigation-bar li {
  display: inline-block;
  padding: 10px;
  background-color: #ccc;
  cursor: pointer;
  position: relative; /* 添加相对定位 */
}

.navigation-bar ul ul {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  top: 100%; /* 子菜单相对于父菜单定位 */
  left: 0;
}

.navigation-bar li:hover ul {
  display: block;
}

.navigation-bar li ul li {
  display: block;
}
</style>
